(function (window, $) {
  /**
   * AJAX 数据请求
   * @param {*} url 请求地址
   * @param {*} success 成功的回调
   * @param {*} method 请求方式，默认 GET
   * @param {*} data 请求参数
   * @param {*} error 失败的回调，默认 undefined
   */
  const request = function ({ url, success, method = "Get", data = {}, error = undefined }) {
    $.ajax({
      type: method,
      url,
      data,
      beforeSend: function (request) {
        request.setRequestHeader("Authorization", localStorage.getItem("token") || "");
      },
      success: function (res) {
        if (res.status) {
          if (success && typeof success === "function") {
            success(res.data);
          }
        } else {
          if (error && typeof error === "function") {
            error(res.message);
          }
        }
      },
      error: function (xhr, _status, _thrown) {
        console.log(xhr.responseText);
        if (error && typeof error === "function") {
          error(xhr.responseText);
        }
      },
    });
  };

  const baseUrl = "http://localhost:58728/api";

  // 查询所有blog
  const reqBlog = function ({ success, data = {} }) {
    request({ url: `${baseUrl}/blog/getall`, success, data });
  };

  // 查询指定分类的blog
  const reqBlogByCategory = function ({ success, data = {} }) {
    request({ url: `${baseUrl}/blog/GetAllByCategory`, success, data });
  };

  // 查询单个blog
  const reqBlogSingle = function ({ success, data }) {
    request({ url: `${baseUrl}/blog/getSingle`, success, data });
  };

  // 删除blog
  const delBlog = function ({ success, data }) {
    request({ url: `${baseUrl}/blog/delete`, success, method: "Post", data });
  };

  // 修改blog
  const uptBlog = function ({ success, data }) {
    request({ url: `${baseUrl}/blog/update`, success, method: "Post", data });
  };

  // 添加blog
  const addBlog = function ({ success, data }) {
    request({ url: `${baseUrl}/blog/insert`, success, method: "Post", data });
  };

  // 查询所有category
  const reqCategory = function ({ success, data = {} }) {
    request({ url: `${baseUrl}/category/getall`, success, data });
  };

  // 登录
  const reqLogin = function ({ success, data = {} }) {
    request({ url: `${baseUrl}/account/Login`, success, method: "Post", data });
  };

  // 注册
  const reqRegister = function ({ success, data = {} }) {
    request({ url: `${baseUrl}/account/register`, success, method: "Post", data });
  };

  // 统计
  const reqBlogStatic = function ({ success }) {
    request({ url: `${baseUrl}/statistics/all`, success });
  };

  window.$$ = {
    request,
    reqBlog,
    reqCategory,
    reqLogin,
    reqBlogStatic,
    delBlog,
    uptBlog,
    addBlog,
    reqBlogSingle,
    reqBlogByCategory,
  };
})(window, $);
